/** storage数据存储格式 */
interface ICacheData {
  /** 过期时间 */
  t: number;
  /** 存储数据 */
  v: any;
}

interface GetStorageInfoSyncOption {
  /** 当前占用的空间大小, 单位 KB */
  currentSize: number
  /** 当前 storage 中所有的 key */
  keys: string[]
  /** 限制的空间大小，单位 KB */
  limitSize: number
}

/** storage兼容处理 */
export default class StorageCompatible {
  constructor() {}

  /** 对数据进行获取 */
  protected queryStorageByKey(key: string): ICacheData|undefined {
    let data: any;
    data = window.localStorage.getItem(key)

    return data ? JSON.parse(data) : undefined
  }

  /** 对数据进行存储 */
  protected saveStorage(key: string, val: ICacheData) {
    const data = JSON.stringify(val)
    return window.localStorage.setItem(key, data)
  }

  /** 获取sotrage信息 */
  protected getStorageInfo = (): GetStorageInfoSyncOption => {
    const getLimitSizeByWebkit = () => {
      const test = (i: number): number => {
        try {
          const arr = new Array(1024 * 1024 * i / 2)
          const str = arr.fill('1').join(',')
          // console.log(str.length / 1024 / 1024, 'test');
          window.localStorage.setItem('test', str)
          // console.log(str.length / 1024 / 1024, true);
          return test(i + 1)
        } catch (error) {
          window.localStorage.removeItem('test')
          return Number((i * 1024).toFixed(2))
        }
      }
      return test(1)
    }

    let keys = Object.keys(window.localStorage)
    let vals: Record<string, any> = {}
    let currentSize = 0

    for (const key of keys) {
      const val = window.localStorage.getItem(key)
      currentSize += val?.length || 0
      vals[key] = val
    }

    window.localStorage.clear()
    let limitSize = getLimitSizeByWebkit()

    for (const key in vals) {
      window.localStorage.setItem(key, vals[key])
    }

    return {
      keys,
      currentSize: Number(currentSize.toFixed(2)),
      limitSize
    };
  };

  /** 对sotrage进行删除 */
  protected deleteStorageByKey(key: string) {
    window.localStorage.removeItem(key)
  }

  /** 对sotrage进行清空 */
  protected clearStorage() {
    window.localStorage.clear()
  }
}
